//
//  BpModel.m
//  project
//
//  Created by 黄建华 on 2018/2/6.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "BpModel.h"

/***************************************************血压模型***********************************************/
@implementation bpSubModel
- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

@end


@implementation BpModel

- (instancetype)init {
    self = [super init];
    if (self) {
        _user_id    = SN_USER.user_id;
        _dateString = [[NSDate date] dateToDayString];
        _SBPAve     = 0;
        _DBPAve     = 0;
        _weekCount  = [NSDate getDaysWeekNumberWithSelectDate:[NSDate date]];
        _monthCount = [NSDate getDaysMonthNumberWithSelectDate:[NSDate date]];
        _dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:[NSDate date] withType:0];
        _dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:[NSDate date] withType:1];
        _yearCount  = [NSDate getDaysYearNumberWithSelectDate:[NSDate date] withType:2];
    }
    return self;
}

+ (BpModel *)initWithDate:(NSDate *)date {
    BpModel *model = [[BpModel alloc] init];
    
    model.dateString = [date dateToDayString];
    model.user_id    = SN_USER.user_id;
    model.DBPAve     = 0;
    model.SBPAve     = 0;
    model.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
    model.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
    model.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
    model.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
    model.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
    return model;
}

+ (BpModel *)getBpModelFromDB {
    BpModel *model = [BpModel getBpModelFromDBWith:[NSDate date]];
    
    return model;
}

+ (BpModel *)getBpModelFromDBWithDayString:(NSString *)string {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, string];
    BpModel *model = [BpModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model            = [[BpModel alloc] init];
        model.dateString = string;
        model.user_id    = SN_USER.user_id;
        NSDate    *date= [NSDate dateByString:string];
        model.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
        model.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
        model.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
        model.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
        model.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
        [model updateToDB];
    }
    return model;
}

+ (BpModel *)getBpModelFromDBWith:(NSDate *)date {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, [date dateToDayString]];
    BpModel *model = [BpModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model = [BpModel pedometerSaveEmptyModelToDBWithDate:date isSaveAllDay:NO];
    }
    return model;
}

- (void)updateToDBSafely {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, self.dateString];
    BpModel *model = [BpModel searchSingleWithWhere:where orderBy:nil];
    
    if (model) {
        [BpModel updateToDB:self where:nil];
    }
}

+ (BpModel *)pedometerSaveEmptyModelToDBWithDate:(NSDate *)date isSaveAllDay:(BOOL)save {
    BpModel *model = [BpModel initWithDate:date];
    
    [BpModel creatEmptyDataArrayWithModel:model];
    if (![date compareWithDate:[NSDate date]] &&
        [date timeIntervalSince1970] < [[NSDate date] timeIntervalSince1970]) {
        // NSLog(@"model.isSaveAllDay = ..%@", date);
        if (save) {
            model.isSaveAllDay = YES;
        }
    }
    
    [model saveToDB];
    
    return model;
}

// 为模型创建空值的对象
+ (void)creatEmptyDataArrayWithModel:(BpModel *)model {
}

// 表名
+ (NSString *)getTableName {
    return @"BpModel";
}

// 复合主键
+ (NSArray *)getPrimaryKeyUnionArray {
    return @[@"user_id", @"dateString"];
}

// 表版本
+ (int)getTableVersion {
    return 1;
}

+ (void)initialize {
    [super initialize];
    
    [self bindYYJSONKey:@"min" toProperty:@"SBPAve"];
    [self bindYYJSONKey:@"max" toProperty:@"DBPAve"];
    [self bindYYJSONKey:@"data" toProperty:@"detailData"];
    [self bindYYJSONKey:@"date" toProperty:@"dateString"];
    
    [self removePropertyWithColumnName:@"detailData"];
}

+ (void)updateCheckBP {
    NSLog(@"手动检测血压数据同步完成>>>");
    [SN_Net updateEveryModelWithType:HJUpdateBp];
}

- (void)updateRealBPData:(NSInteger)Sbp withBp:(NSInteger)Dbp {
    [SN_PublicClass.bpCheckArray addObject:StrByInt(Sbp)];
    [SN_PublicClass.bpCheckArray addObject:StrByInt(Dbp)];
    SN_PublicClass.bpValueString = [NSString stringWithFormat:@"%d ~ %d", Sbp, Dbp];
    if (SN_PublicClass.bpBlock) {
        SN_PublicClass.bpBlock(Sbp, Dbp);
    }
}

- (void)updateRealBPDataEnd:(NSArray *)bpArray {
    NSLog(@"updateRealBPDataEnd: >>>>>%@", bpArray);
    SN_PublicClass.bpCheckArray = [NSMutableArray array];
    [SN_PublicClass.bpCheckArray addObjectsFromArray:bpArray];
    
    int a = [[SN_PublicClass.bpCheckArray firstObject]intValue];
    int b = [[SN_PublicClass.bpCheckArray lastObject]intValue];
    
    bpSubModel *model = [[bpSubModel alloc] init];
    model.count = [NSDate getCurrentMinTotal]/15;
    int currentMin = [NSDate getCurrentMinTotal];
    model.countMins = currentMin;
    NSDate *nowDate      = [NSDate date];//现在的UTC时间也可以写成[[NSDate alloc] init];
    NSDate *startOfToday = [[NSCalendar currentCalendar] startOfDayForDate:nowDate];
    
    NSDate   *date = [startOfToday dateByAddingTimeInterval:currentMin *60];
    NSString *time = [date dateToStringHourMin];
    model.updateTime = time;
    model.SBPValue   = [[SN_PublicClass.bpCheckArray firstObject] integerValue];
    model.DBPValue   = [[SN_PublicClass.bpCheckArray lastObject] integerValue];
    //            model.data       = [NSString stringWithFormat:@"%d,%d", model.SBPValue, model.DBPValue];
    
    BpModel        *tmodel     = SN_PublicClass.todayBp;
    NSMutableArray *checkArray = [NSMutableArray arrayWithArray:tmodel.bpSuArray];
    [checkArray addObject:model];
    
    NSMutableArray *sbpArr  = [NSMutableArray array];
    NSMutableArray *dbpArr  = [NSMutableArray array];
    int            sbpTotal = 0;
    int            dbpTotal = 0;
    for (int i = 0; i < checkArray.count; i++) {
        bpSubModel *bpModel = [checkArray objectAtIndex:i];
        [sbpArr addObject:StrByInt(bpModel.SBPValue)];
        [dbpArr addObject:StrByInt(bpModel.DBPValue)];
        sbpTotal += bpModel.SBPValue;
        dbpTotal += bpModel.DBPValue;
    }
    
    tmodel.SBPAve    = sbpTotal / sbpArr.count;
    tmodel.DBPAve    = dbpTotal / dbpArr.count;
    tmodel.bpSuArray = [NSMutableArray arrayWithArray:checkArray];
    [tmodel updateToDB];
}

//同步下载数据需要的
- (void)saveToDBByDownload
{
    NSDate *date= [NSDate dateByString:self.dateString];
    self.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
    self.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
    self.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
    self.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
    self.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
    
    NSArray *array = (NSArray *)[self.detailData parseJSONString];
    if ([array isKindOfClass:NSArray.class] && array.count > 0) {
        self.bpSuArray = [NSMutableArray array];
        for (int i = 0; i < array.count ; i++) {
            NSDictionary *dict = array[i];
            if ([dict isKindOfClass:NSDictionary.class]) {
                if (dict[@"time"] && dict[@"systolic"] && dict[@"diastolic"]) {
                    bpSubModel *model = [[bpSubModel alloc] init];
                    model.SBPValue = [dict[@"systolic"] integerValue];
                    model.DBPValue = [dict[@"diastolic"] integerValue];

                    NSString *time = @"";
                    NSArray *timeArrayS = [dict[@"time"] componentsSeparatedByString:@" "];
                    if (timeArrayS.count ==2) {
                        model.updateTime = dict[@"time"];
                        time = [timeArrayS lastObject];
                    }
                    else
                    {
                        NSString *updateTimeString = [NSString stringWithFormat:@"%@ %@",self.dateString,dict[@"time"]];
                        model.updateTime = updateTimeString;
                        time = dict[@"time"];
                        
                    }
                    
                    NSString *timeS     = time;
                    NSString *timeSS = @"";
                    if (timeS.length >=5) {
                        timeSS = [timeS substringWithRange:NSMakeRange(0, 5)];
                    }
                    else
                    {
                        timeSS = [timeS substringWithRange:NSMakeRange(0, timeS.length)];
                    }
                    NSArray *timeArray = [timeSS componentsSeparatedByString:@":"];
                    int timeInt = [[timeArray firstObject]intValue]*60 +[[timeArray lastObject]intValue];
                    model.count = timeInt/15;
                    model.countMins = timeInt;
                    [self.bpSuArray addObject:model];
                }
            }
        }
    }
        
    NSMutableArray *sbpArr  = [NSMutableArray array];
    NSMutableArray *dbpArr  = [NSMutableArray array];
    int            sbpTotal = 0;
    int            dbpTotal = 0;
    for (int i = 0; i < self.bpSuArray.count; i++) {
        bpSubModel *bpModel = [self.bpSuArray objectAtIndex:i];
        [sbpArr addObject:StrByInt(bpModel.SBPValue)];
        [dbpArr addObject:StrByInt(bpModel.DBPValue)];
        sbpTotal += bpModel.SBPValue;
        dbpTotal += bpModel.DBPValue;
    }
    self.SBPAve    = sbpTotal / sbpArr.count;
    self.DBPAve    = dbpTotal / dbpArr.count;
    
    
    NSString *todayStr = [[NSDate date] dateToDayString];
    if (self.dateString != todayStr) {
        self.isSaveAllDay = YES;
    }
    
    [self updateToDB];
}

@end

